package net.tngou.iask.dao;

import java.util.ArrayList;
import java.util.List;

import net.tngou.iask.jdbc.PageUtil;
import net.tngou.iask.jdbc.QueryHelper;
import net.tngou.iask.pojo.POJO;
import net.tngou.iask.util.IPv4Util;
import net.tngou.iask.util.StringUtil;

/**
 * 日志操作
 * @author tngou@tngou.net
 *
 */
public class LogDao extends BaseDao {

	
	/**
	 * 取得实体日志
	 * @param page 当前页
	 * @param size 大小
	 * @param main 实体
	 * @param level 等级
	 * @param keyword 关键词
	 * @return
	 */
	public PageUtil getPage(int page,int size,long main,long level,String keyword) {
		List<?> list=new ArrayList<>();
		int total=0;
		String sql_r="SELECT log.*,user.name  ,INET_NTOA(ip) AS ipsting";
		String sql_t="SELECT COUNT(log.id) ";
		String sql_o=" ORDER BY id DESC";//排序
		String sql=" FROM `"+POJO.DABASE+"_log` log,`"+POJO.DABASE+"_user` user"
				+ " WHERE  log.main=? AND log.level=? AND user.id=log.user ";
		if(StringUtil.isNotEmpty(keyword))
		{
			sql=sql+" AND (user.name LIKE ? OR log.description LIKE ? OR ip=?)";
			
			Object[] params={main,level,keyword+"%",keyword+"%",IPv4Util.StrToLong(keyword)};
			list=QueryHelper.query_page(sql_r+sql+sql_o, page, size, params);			
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}else{
			Object[] params={main,level};
			list=QueryHelper.query_page(sql_r+sql+sql_o, page, size, params);
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}		
		return new PageUtil(list, page, size, total);
		
	}
	
	/**
	 * 取得实体对应的用户日志
	 * @param page 当前页
	 * @param size 大小
	 * @param main 实体
	 * @param user 用户
	 * @param level 等级
	 * @param keyword 关键词
	 * @return
	 */
	public PageUtil getPage(int page,int size,long main,long user,long level,String keyword) {
		List<?> list=new ArrayList<>();
		int total=0;
		String sql_r="SELECT log.*,user.name ,INET_NTOA(ip) AS ipsting";
		String sql_t="SELECT COUNT(log.id) ";
		String sql_o=" ORDER BY id DESC";//排序
		String sql=" FROM `"+POJO.DABASE+"_log` log,`"+POJO.DABASE+"_user` user"
				+ " WHERE  log.main=? AND  log.user=? AND log.level=? AND user.id=log.user ";
		if(StringUtil.isNotEmpty(keyword))
		{
			sql=sql+" AND (user.name LIKE ? OR log.description LIKE ? OR ip=?)";
			Object[] params={main,user,level,keyword+"%",keyword+"%",IPv4Util.StrToLong(keyword)};
			list=QueryHelper.query_page(sql_r+sql+sql_o, page, size, params);			
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}else{
			Object[] params={main,user,level};
			list=QueryHelper.query_page(sql_r+sql+sql_o, page, size, params);
			total=(int) QueryHelper.stat(sql_t+sql, params);
		}		
		return new PageUtil(list, page, size, total);
		
	}
		
}
